package com.lh.postern.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.lh.pojo.Pic;
import com.lh.postern.service.impl.PicServiceImpl;

@Controller
public class PicController {
	
	@Autowired
	PicServiceImpl picServiceImpl;
	
	@RequestMapping("/upload")
	public String upload(MultipartFile file,HttpServletRequest request) {
		String page = "forward:add.jsp";
		try {
			//路径
			String path = request.getServletContext().getRealPath("/files");
			//可以考虑重名
			//
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path+File.separator+file.getOriginalFilename()));
			//把数据保存到数据库中
			Pic pic = new Pic();
			pic.setPath(file.getOriginalFilename());
			int flag = picServiceImpl.insertPic(pic);
			if(flag > 0) {
				page = "/all";
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return page;
	}
	
	@RequestMapping("/all")
	public ModelAndView findAllPics() {
		List<Pic> list = picServiceImpl.findAll();
		ModelAndView mv = new ModelAndView("forward:all.jsp");
		mv.addObject("list",list);
		return mv;
	
	}
	
	@RequestMapping("/del")
	public String findAllPics(int id) {
		int flag = picServiceImpl.deletePic(id);
		return "/all";
	}
	
}
